<?php
namespace Todo\Model\Rate;

use Todo\Model\BaseModel;

class RecordModel extends BaseModel
{
    protected $order = 'id DESC';

    public $tableName = 'rate_record';

    public $_validate = array(
        array('project_id', 'require', '请选择项目'),
        array('add_user', 'require', '必须有打分人'),
        array('add_name', 'require', '必须有打分人'),
        array('user_id', 'require', '必须有被评人'),
        array('name', 'require', '必须有被评人')
    );
    
    protected $_auto = array(
        array('total', 0, self::MODEL_INSERT),
        array('add_ip', 'get_client_ip', self::MODEL_INSERT, 'function'),
        array('add_time', 'auto_datetime', self::MODEL_INSERT, 'function'),
        array('tnt_id', 'auto_tnt', self::MODEL_INSERT, 'function')
    );

    /**
     * 判断评价记录是否存在
     * @param $projectId
     * @param $userId
     * @param $addUser
     * @return array|bool|mixed
     */
    public function checkRecord($projectId, $userId, $addUser){
        $recordInfo = array(
            'project_id'=>$projectId,
            'user_id'=>$userId,
            'add_user'=> $addUser
        );
        $record = $this->where($recordInfo)->find();
        if(!$record){
            $recordInfo['add_ip'] = get_client_ip();
            $recordInfo['tnt_id'] = auto_tnt();
            $recordInfo['add_time'] = date('Y-m-d H:i:s');
            $users = D('Todo/Rate/User')->where(array('user_id'=>array('in', array($recordInfo['user_id'], $recordInfo['add_user']))))->select();
            foreach ($users as $u){
                if($u['user_id'] == $recordInfo['add_user']) $recordInfo['add_name'] = $u['name'];
                else if($u['user_id'] == $recordInfo['user_id']) $recordInfo['name'] = $u['name'];
            }
            $recordId = $this->insert($recordInfo);
            if($recordId){
                $record = $recordInfo;
                $record['id'] = $recordId;
            }else{
                return false;
            }
        }
        return $record;
    }
    
}